<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <div id="app1"></div>
    <div id="app2"></div>
    <hr/>
    <div id="app3"></div>
    <script src="../react-lib/babel.min.js"></script>
    <script src="../react-lib/react.development.js"></script>
    <script src="../react-lib/react-dom.development.js"></script>
    <!-- 使用 PropTypes 进行类型检查 -->
    <script src="../react-lib/prop-types.js"></script> 
    <script type="text/babel"> 
    /**
    * 
    */
     class App extends React.Component{
         constructor(props){
             super(props)
             this.state = {
                 todos : [
                     '吃饭',
                     '睡觉',
                     '打豆豆'
                 ]
             }
             // 只要是自定义的就要bind
            this.addTodo = this.addTodo.bind(this)
         } 
        render(){ 
            return (
                <div>
                    <h1>Simple ToDo List</h1>
                    <Add todos={this.state.todos} addTodo={this.addTodo}/>
                    <List todos={this.state.todos}/>
                </div>
            )
        }
        addTodo(item){
            const {todos} = this.state
            todos.unshift(item)
            this.setState(todos)
        }
    }
    class Add extends React.Component{
        constructor(props){
            super(props)
            this.add = this.add.bind(this)
        } 
        render(){ 
            return (
                <div>
                    <input type="text" ref={input => this.todoInput = input}/>
                    <button onClick={this.add}>Add #{this.props.todos.length+1}</button>
                </div>
            )
        }
        add(){
            const todo = this.todoInput.value.trim()
            if(!todo){
                return
            }
            this.props.addTodo(todo)
            this.todoInput.value = ''
        }
    }
    Add.propTypes = {
        todos: PropTypes.array.isRequired,
        addTodo: PropTypes.func.isRequired
    }

    class List extends React.Component{
         constructor(props){
             super(props)
         } 
        render(){ 
            return (
                <ul>
                    {this.props.todos.map((item,index)=>(
                        <li key={index}>{item}</li>
                    ))}
                </ul>
            )
        } 
    }
    List.propTypes = {
        todos: PropTypes.array.isRequired
    }


    ReactDOM.render(<App/>,document.getElementById('app1'))
    </script>
</body>
</html>